<template>
    <MainSlot v-loading="loading">
        <template v-slot:btn>
            <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
        </template>
        <template v-slot:table>
            <div class="tableList">
                <div class="tableModle tableModleLeft">
                    <div class="tableTilte">已选品种</div>
                    <TableData :openColumn="false" :config="table_config" :tableThead="tableThead"
                        :dataList="dataList_left" :loading="loading" @selection-change="selectionChange">
                        <template v-slot:pictureId="{ row }">
                            <span v-show="row.pictureNo" class="pointer primary"
                                @click="addImage(row, 'edit')">编辑图片</span>
                            <span v-show="!row.pictureNo" class="pointer primary"
                                @click="addImage(row, 'add')">添加图片</span>
                        </template>
                        <template v-slot:showPicture="{ row }">
                            <span v-show="row.pictureNo" class="pointer primary"
                                @click="handleImgs(row.pictureNo)">查看</span>
                        </template>
                        <template v-slot:breedType="{ row }">
                            <span>{{ row.breedType ? getBreedTypeName(row.breedType).join('；') : '' }}</span>
                        </template>
                    </TableData>
                    <div class="imageDom" v-show="closeImg">
                        <i class="el-icon-close" @click.stop="closeImg = false"></i>
                        <el-image style="width: 90vw; height: 90vh" :src="handleImgUrl" fit="contain"></el-image>
                    </div>
                </div>
                <div class="line"></div>
                <div class="tableModle tableModleRight">
                    <div class="tableTilte">所有品种</div>
                    <div class="searchFormModule">
                        <el-input class="w50p" v-model="searchForm_right.plantVarietyName" clearable
                            placeholder="搜索养殖品种名称" @change="() => { page_right = 1; plantVariety() }"></el-input>
                        <el-select class="w50p" v-model="searchForm_right.plantTypeNo" filterable clearable
                            placeholder="请选择养殖类型" @change="() => { page_right = 1; plantVariety() }">
                            <el-option v-for="item, index in plantTypeList" :key="index" :label="item.plantTypeName"
                                :value="item.plantTypeNo">
                            </el-option>
                        </el-select>
                    </div>
                    <TableData id="tableThead_2" :tableThead="tableThead_2" :isSelect="true" :openColumn="false"
                        :dataList="dataList_right" :loading="loading" @selection-change="selectionChange_right">
                        <template v-slot:sowingDate="{ row }">
                            <span>{{ `${row.sowingStartDate || ''}~${row.sowingEndDate || ''}` }}</span>
                        </template>
                    </TableData>
                </div>
            </div>
        </template>
        <template v-slot:pagination>
            <div class="tableList">
                <div class="tableModle">
                    <Pagination @size-Change="handleSizeChange" :size="size_left" @current-change="handleCurrentChange"
                        :page="page_left" :total="total_left">
                    </Pagination>
                </div>
                <div class="tableModle">
                    <Pagination @size-Change="handleSizeChange_right" :size="size_right"
                        @current-change="handleCurrentChange_right" :page="page_right" :total="total_right">
                    </Pagination>
                </div>
            </div>
        </template>
        <template v-slot:dialogModule>
            <div class="guideBox" v-if="isGuide">
                <div class="routerInfo" :style="guideStyle"
                    v-if="isGuide && guideInfo.index > 0 && guideInfo.procedure.length">
                    <div class="guideText">{{ guideIndex + 1 }}. {{ guideInfo.procedure && guideInfo.procedure.length >
                        0 ?
                        guideInfo.procedure[guideIndex]
                        : '' }}</div>
                    <div class="guideNext" @click="guideNext" v-if="guideInfo.procedure.length > (guideIndex + 1)">下一步
                    </div>
                </div>
            </div>
            <AddEdit :title="'提交养殖品种'" @closeDialog="closeDialog" :dialogVisible="dialogVisible" :data="formData"
                :plantTypeList="plantTypeList">
            </AddEdit>
            <AddType :title="'养殖类型'" @closeDialog="closeDialog" :dialogVisible="dialogVisible_type"
                :list="addSelectionList">
            </AddType>
            <AddEditImage :title="'编辑图片'" @closeDialog="closeDialog" :addEditFlag="addEditFlag"
                :dialogVisible="dialogVisible_image" :data="formData">
            </AddEditImage>
        </template>
    </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import AddEdit from './components/addEdit.vue';
import AddType from './components/addType.vue';
import AddEditImage from './components/addEditImage.vue';
import publicLnterface from '@/api/publicLnterface';
import varietyManagement from '@/api/basicInformation/varietyManagement';

export default {
    components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit, AddType, AddEditImage },
    computed: {
        guideInfo() {
            return this.$store.state.user.guideInfo;
        },
        isGuide() {
            return this.$store.state.user.isGuide || ''
        },
    },
    data() {
        return {
            guideIndex: 0,
            guideStyle: {},
            closeImg: false,
            addEditFlag: 'add',
            loading: false,
            dialogVisible: false,
            dialogVisible_type: false,
            dialogVisible_image: false,
            formData: {},
            page: 1,
            selectIndex: 0,
            btnList: ['submitData', 'add', 'delete'],
            dataList: [
                {
                    item1: '虾类',
                    item2: '黑虎虾',
                    item3: '1月-10月',
                    item4: ''
                }, {
                    item1: '虾类',
                    item2: '皮皮虾',
                    item3: '6月-9月',
                    item4: ''
                }
            ],
            plantTypeList: [],
            addSelectionList: [],
            delSelectionList: [],
            tableThead: [
                { isShow: true, label: '品种类型', prop: 'plantTypeName' },
                { isShow: true, label: '品种名称', prop: 'plantVarietyName' },
                { isShow: true, label: '品种图片', slotName: 'pictureId' },
                { isShow: true, label: '查看图片', slotName: 'showPicture' }
                // breedTypeObj
            ],
            tableThead_2: [
                { isShow: true, label: '品种类型', prop: 'plantTypeName' },
                { isShow: true, label: '品种名称', prop: 'plantVarietyName' },
                { isShow: true, label: '最佳养殖时间', slotName: 'sowingDate' }
            ],
            // 配置项
            table_config: {
                isCheckBox: true,
                isOperation: true,
                // 表格操作列
                operation: {
                    label: '操作',
                    width: '150',
                    cols: [
                        {
                            label: '删除',
                            type: 'danger',
                            flag: 'delete',
                            handleRow: this.handleRow
                        }
                    ]
                },
            },
            page_right: 1,
            size_right: 10,
            total_right: 10,

            page_left: 1,
            size_left: 10,
            total_left: 10,

            dataList_left: [],
            dataList_right: [],
            searchForm_left: {},
            searchForm_right: {},
            handleImgUrl: '',
            breedTypeObj: {
                "HANGING_WATER_BREED": '吊水养殖',
                "TRADITION_BREED": '传统养殖',
                "CIRCULATE_BREED": '循环水养殖',
                "RUNWAY_BREED": '跑道养殖'
            }
        }
    },
    watch: {
        guideInfo: {
            handler(v) {
                this.setGuide(v)
                console.log(v)
            },
            deep: true
        }
    },
    mounted() {
        this.plantVariety();
        this.plantType();
        this.queryPageByCondition();
        setTimeout(() => {
            this.setGuide(this.guideInfo || {})
        }, 1000);
    },
    methods: {
        guideNext() {
            let { index, procedure } = this.guideInfo
            this.$store.dispatch("user/getGuideInfo", {
                procedure: procedure,
                index: index + 1
            });
        },
        setGuide(v) {
            let { index } = v;
            this.guideIndex = index;
            let tree = document.querySelectorAll('#tableThead_2 .el-table')[0];
            let btn = document.getElementById('guide_add');
            this.resetGuide(tree);
            this.resetGuide(btn);
            if (index == 1) {
                tree.className += " guide-name";
                this.guideStyle = {
                    top: '30%',
                    right: '54%',
                    wayFlag: 'right'
                }
            } else if (index == 2) {
                btn.className += " guide-name";
                this.guideStyle = {
                    top: '12%',
                    right: '36%',
                    wayFlag: 'right'
                }
            }
        },
        resetGuide(node) {
            node && (node.className = node.className.replace("guide-name", ""))
        },
        getBreedTypeName(type) {
            let list = type.split(',')
            let typeName = []
            list.forEach(type => {
                typeName.push(this.breedTypeObj[type])
            })
            console.log(typeName, list)
            return typeName
        },
        queryPageByCondition() {
            let params = {
                page: this.page_left,
                size: this.size_left,
                entity: {
                    // breedType: this.$store.state.user.breedType_template,
                    organizationNo: sessionStorage.organizationNo,
                }
            }
            varietyManagement.queryPageByCondition(params).then(res => {
                console.log(res)
                if (res.code == 1) {
                    this.dataList_left = res.data.content;
                    this.total_left = res.data.totalElements;
                } else {
                    this.dataList_left = [];
                }
            }).catch(err => {
                console.log(err)
            })
        },
        async plantVariety() {
            let { data } = await publicLnterface.plantVariety({
                page: this.page_right,
                size: this.size_right,
                entity: {
                    ...this.searchForm_right
                }
            });
            this.total_right = data.totalElements;
            this.dataList_right = data.content;
        },
        handleImgs(e) {
            publicLnterface.seeimgmets(e).then(res => {
                if (res.code === 1) {
                    if (res.data) {
                        this.handleImgUrl = 'data:image/png;base64,' + res.data.pictureData;
                        this.closeImg = true;
                    } else {
                        this.handleImgUrl = '';
                        this.closeImg = false;
                        this.$message.warning('未查询到图片信息，请重新编辑图片！')
                    }
                } else {
                    this.$message.warning("暂无图片！！！");
                }
            });
        },
        async plantType() {
            let { data } = await publicLnterface.plantType();
            this.plantTypeList = data;
            this.plantTypeList.forEach(item => {
                if (item.children && item.children.length > 0) {
                    this.plantTypeList = this.plantTypeList.concat(item.children)
                }
            });
        },
        //删除本地数据
        delList(deleteList) {
            let list = deleteList || this.delSelectionList;
            if (list.length == 0) return
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await varietyManagement.delList(list);
                if (res.code == 1) {
                    this.$message.success(res.msg || '删除成功');
                    this.queryPageByCondition();
                } else {
                    this.$message.warning(res.msg || '删除失败');
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleCurrentChange(page) {
            console.log(page)
            this.page_left = page;
            this.queryPageByCondition();
        },
        handleCurrentChange_right(page) {
            this.page_right = page;
            this.plantVariety();
        },

        handleSizeChange(size) {
            this.size_left = size;
            this.queryPageByCondition();
        },
        handleSizeChange_right(size) {
            this.size_right = size;
            this.plantVariety();
        },
        addImage(row, flag) {
            this.addEditFlag = flag;
            this.dialogVisible_image = true;
            this.formData = JSON.parse(JSON.stringify(row))
        },
        // 操作方法
        handleRow(rowData, item) {
            console.log(rowData, item);
            if (item.flag == 'delete') {
                this.delList([rowData.plantVarietyNo])
            }
        },
        // 多选方法
        selectionChange(val) {
            console.log(val);
            this.delSelectionList = []
            val.forEach(item => {
                this.delSelectionList.push(item.plantVarietyNo)
            })
        },
        selectionChange_right(val) {
            this.addSelectionList = []
            val.forEach(item => {
                this.addSelectionList.push(item.plantVarietyNo)
            })
            console.log(this.addSelectionList)
        },
        //获取选中Btn
        async getBtnEvent(flag) {
            if (flag == 'submitData') {
                this.dialogVisible = true;
            } else if (flag == "add") {
                if (this.addSelectionList.length == 0) {
                    this.$message.warning('请先选择添加项目')
                    return
                }
                let list = this.addSelectionList.map(no => {
                    return this.dataList_right.filter(e => e.plantVarietyNo == no)[0]
                })
                console.log(list);
                varietyManagement.importPublicList('', list).then(res => {
                    this.$message[res.code == 1 ? 'success' : 'warning'](res.code == 1 ? '操作成功' : res.msg || '操作失败');
                    this.queryPageByCondition();
                    this.addSelectionList = [];
                }).catch(err => {
                    this.$message.error(err);
                })
            } else if (flag == 'delete') {
                if (this.delSelectionList.length > 0) {
                    this.delList(this.delSelectionList)
                } else {
                    this.$message.warning('请先选择表单数据项后再删除！')
                }
            }
        },
        //关闭弹窗
        closeDialog() {
            this.dialogVisible = false;
            this.dialogVisible_type = false;
            this.dialogVisible_image = false;
            this.addSelectionList = [];
            this.delSelectionList = [];
            this.queryPageByCondition();
        },
    }
};
</script>
<style lang="scss" scoped>
.tableModleLeft {
    .app-container {
        height: calc(100% - 32px);
    }
}

.tableModleRight {
    .app-container {
        height: calc(100% - 70px);
    }
}

.tableList {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;

    .line {
        width: 0;
        height: 100%;
        border-left: 1px solid #e9e9e9;
    }

    .tableModle {
        width: calc(50% - 10px);

        .tableTilte {
            font-size: 14px;
            line-height: 40px;
            color: #4381b5;
        }
    }
}

.pointer {
    margin-right: 5px;
}

.searchFormModule {
    width: 70%;
    display: flex;
    justify-content: flex-start;
    margin-bottom: 10px;

    .w50p {
        margin-right: 10px;
    }
}

.imageDom {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    transform: translate(-50% -50%);
    background: #0000008e;
    z-index: 999999;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-icon-close {
        position: fixed;
        top: 10px;
        right: 10px;
        font-size: 38px;
        color: #ffffff;
        cursor: pointer;
    }
}

.guideBox {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #00000030;
    z-index: 10;
}


.routerInfo {
    max-width: 400px;
    min-width: 300px;
    padding: 10px;
    background-color: #FF9243;
    color: #ffffff;
    position: fixed;
    z-index: 9999;

    .guideText {
        width: 100%;
        text-align: left;
        line-height: 26px;
    }

    .guideNext {
        width: 100px;
        margin-top: 15px;
        background-color: #e4a579;
        border: 1px solid #c65504;
        border-radius: 4px;
        text-align: center;
        line-height: 28px;
        cursor: pointer;

        &:hover {
            background-color: #d88244;
        }
    }
}

::v-deep {

    .el-table--border::after,
    .el-table--group::after,
    .el-table::before {
        z-index: 0;
    }

    .el-checkbox__inner {
        z-index: 0;
    }
}
</style>